package com.jstyle.jclife.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.jstyle.blesdk.Util.ResolveUtil;
import com.jstyle.blesdk.Util.SingleDealData;
import com.jstyle.blesdk.model.Clock;
import com.jstyle.jclife.R;
import com.jstyle.jclife.adapter.MyWheelAdapter;
import com.jstyle.jclife.ble.BleManager;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.view.widget.views.WheelView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AlarmSetActivity extends BaseActivity {

    @BindView(R.id.bt_clock_cancel)
    Button btClockCancel;
    @BindView(R.id.bt_clock_confim)
    Button btClockConfim;


    @BindView(R.id.radio_normal)
    RadioButton radioNormal;
    @BindView(R.id.radio_Drink)
    RadioButton radioDrink;
    @BindView(R.id.radio_Medicine)
    RadioButton radioMedicine;
    @BindView(R.id.radioGroup_gender)
    RadioGroup radioGroupGender;
    @BindView(R.id.bt_weekContent)
    Button btWeekContent;
    @BindView(R.id.clock_set_title)
    Button clockSetTitle;
    @BindView(R.id.wheelView_hour)
    WheelView wheelViewHour;
    @BindView(R.id.wheelView_min)
    WheelView wheelViewMin;
    private AlertDialog weekDialog;
    @BindArray(R.array.week)
    String[] weekArray;
    private int[] weekPosition;
    private Clock clock;
    private AlertDialog alertDialog;
    private List<Clock> clockList;
    private int clockId;
    private List<String> hourList;
    private List<String> minList;
    private MyWheelAdapter wheelAdapterHour;
    private MyWheelAdapter wheelAdapterMin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_set);
        ButterKnife.bind(this);
        init();
    }
    private List<String> getListData(int start, int end) {
        List<String> list = new ArrayList<>();
        for (int i = start; i < end; i++) {
            list.add(String.format("%02d", i));
        }
        return list;
    }

    private void init() {
        ScreenUtils.setTitleTypeface(clockSetTitle);
        hourList = getListData(0, 24);
        minList = getListData(0, 60);
        wheelAdapterHour = new MyWheelAdapter(this, hourList, 0, 24, 14);
        wheelAdapterMin = new MyWheelAdapter(this, minList, 0, 24, 14);
        wheelViewHour.setVisibleItems(7);
        wheelViewMin.setVisibleItems(7);

        wheelAdapterHour.setCenterColor(getResources().getColor(R.color.wheelViewCenter_color));
        wheelAdapterMin.setCenterColor(getResources().getColor(R.color.wheelViewCenter_color));
        wheelViewHour.setViewAdapter(wheelAdapterHour);
        wheelViewMin.setViewAdapter(wheelAdapterMin);
        //timePickerClockSet.setIs24HourView(true);
        clockId = getIntent().getIntExtra("clockid", -1);
        clockList = (List<Clock>) getIntent().getSerializableExtra(ClockListActivity.KEY_CLOCK_LIST);
        weekPosition = new int[7];
        if (clockId != -1) {
            clock = clockList.get(clockId);
            String content = clock.getContent();
            int hour = clock.getHour();
            int min = clock.getMinute();
            wheelViewHour.setCurrentItem(hour);
            wheelViewMin.setCurrentItem(min);
            int type = clock.getType();
            int week = clock.getWeek();
            initGroup(type);
            String weekString = ResolveUtil.getByteString((byte) week);
            String[] weekArrs = weekString.split("-");
            for (int i = 0; i < 7; i++) {
                if (weekArrs[i].equals("1")) {
                    weekPosition[i] = 1;
                }
            }
            showWeekText();
        } else {
            clockSetTitle.setText(R.string.Add_Alarm);
            String weekString = ResolveUtil.getByteString((byte) 255);
            String[] weekArrs = weekString.split("-");
            for (int i = 0; i < 7; i++) {
                if (weekArrs[i].equals("1")) {
                    weekPosition[i] = 1;
                }
            }
            showWeekText();
        }
    }

    private void showWeekText() {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < weekPosition.length; i++) {
            if (weekPosition[i] == 1) {
                stringBuffer.append(weekArray[i]).append(",");
            }
        }
        String weekString = stringBuffer.toString();
        if (!TextUtils.isEmpty(weekString)) {
            weekString = weekString.substring(0, weekString.length() - 1);
        }
        btWeekContent.setText(weekString);
    }

    @OnClick({R.id.bt_week, R.id.bt_clock_cancel, R.id.bt_clock_confim})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_clock_cancel:
                setResult(RESULT_CANCELED);
                finish();
                break;
            case R.id.bt_clock_confim:

                updateClock();
                break;
            case R.id.bt_week:
                showWeekDialog();
                break;
        }
    }

    private void initGroup(int type) {
        int id = R.id.radio_normal;
        switch (type) {
            case 1:
                id = R.id.radio_normal;
                break;
            case 2:
                id = R.id.radio_Medicine;
                break;
            case 3:
                id = R.id.radio_Drink;
                break;
            case 4:
                id = R.id.radio_food;
                break;
        }
        radioGroupGender.check(id);
    }

    private void showWeekDialog() {
        boolean[] checked = new boolean[7];
        for (int i = 0; i < 7; i++) {
            checked[i] = weekPosition[i] == 1;
        }
        weekDialog = new AlertDialog.Builder(this)
                .setMultiChoiceItems(weekArray, checked, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        weekPosition[which] = isChecked ? 1 : 0;
                    }
                })
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showWeekText();
                    }
                }).setNegativeButton("Cancel", null).create();

        weekDialog.show();
        ScreenUtils.setDialogButtonTextColor(weekDialog);
    }

    private int getClockType() {
        int id = 0;
        switch (radioGroupGender.getCheckedRadioButtonId()) {
            case R.id.radio_normal:
                id = 1;
                break;
            case R.id.radio_Medicine:
                id = 2;
                break;
            case R.id.radio_Drink:
                id = 3;
                break;
            case R.id.radio_food:
                id=4;
                break;
        }
        return id;
    }

    private int getCheckWeek() {
        int week = 0;
        for (int i = 0; i < 7; i++) {
            if (weekPosition[i] == 1) week += Math.pow(2, i);
        }
        return week;
    }

    private static final String TAG = "AlarmSetActivity";
    private void updateClock() {
        if (!BleManager.getInstance().isConnected()) {
            showToast(getString(R.string.disonnected));
            return;
        }
        int hour = Integer.parseInt(hourList.get(wheelAdapterHour.getCurrentItem()));
        int min = Integer.parseInt(minList.get(wheelAdapterMin.getCurrentItem()));
        int type = getClockType();
        int week = getCheckWeek();
        if (clock == null) {
            clock = new Clock();
            clock.setNumber(clockList.size());
            clock.setEnable(true);
            clockList.add(clock);
        }
        clock.setContent("");
        clock.setHour(hour);
        clock.setMinute(min);
        clock.setType(type);
        clock.setWeek((byte) week);
        byte[] value = SingleDealData.setClockData(clockList);
        int maxLength = MainActivity.phoneDataLength;
        Log.i(TAG, "updateClock:"+maxLength);
        if(maxLength==0)return;
        if (value.length > maxLength) {
            int size = maxLength / 39;//一个包最多发的闹钟个数
            int length = size * 39;//最大闹钟数占用的字节
            if(length==0)return;
            int count = value.length % length == 0 ? value.length / length : value.length / length + 1;//需要多少个包来发送
            for (int i = 0; i <count; i++) {
                int end = length * (i + 1);
                int endLength = length;
                if (end >= value.length) endLength = value.length - length * i;
                byte[] data = new byte[endLength];
                System.arraycopy(value, length * i, data, 0, endLength);
                offerData(data);
            }
            offerData();
        } else {
            writeData(value);
        }
        if (alertDialog == null) {
            alertDialog = new AlertDialog.Builder(this,R.style.appalertdialog)
                    .setMessage(R.string.Successful)
                    .setNegativeButton(getString(R.string.Confirm), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            setResult(RESULT_OK);
                            finish();
                        }
                    }).setCancelable(false).create();

        }
        alertDialog.show();
        ScreenUtils.setDialogButtonTextColor(alertDialog);
    }

}
